# Copyright (c) 2007 Fabio Makoto Akita
# 
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
# 
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

# Author: AkitaOnRails (www.akitaonrails.com)
# Support: Surgeworks LLC (www.surgeworks.com)

#
# Implements a way for a complete table dump to CSV file
# and a way to import this complete data set again
#

require 'fastercsv'

class Array
  def to_csv_file(tmp_file = nil)
    tmp_file = File.join(RAILS_ROOT, 'tmp', "#{UUID.timestamp_create().to_s}.csv") unless tmp_file
    
    FasterCSV.open(tmp_file, 'w') do |csv|
      unless self.empty?
        columns = self.first.class.columns.map { |col| col.name.to_sym }
        csv << columns
        self.each do |row|
          csv << columns.collect { |col| row[col] }
        end
      end
    end
    
    tmp_file
  end
end

class << ActiveRecord::Base
  def to_csv_file(tmp_file, finder_options = {})
    find(:all, finder_options).to_csv_file(tmp_file)
  end
  
  def import_from_csv(tmp_file = nil)
    raise ActiveRecord::CSVImportException.new("File #{tmp_file} not find.") unless !tmp_file.nil? && File.exists?(tmp_file)
    total = 0
    begin
      # technically, sqlite performs better with everything inside a 
      # transaction to avoid closing and reopening the data file
      self.transaction do
        # turn off Replica tracking
        Replica.track_replica = false
        ActiveRecord::Base.record_userstamps = false
        ActiveRecord::Base.record_timestamps = false
        
        # empty the current table for a clean import
        # this is necessary or we risk duplicate keys
        # - prepared for the acts_as_paranoid
        self.respond_to?("deleted_attribute") ? self.delete_all! : self.delete_all 
        columns = nil
        FasterCSV.foreach(tmp_file) do |row|
          unless columns
            columns = row.map(&:to_sym)
            next
          end
          begin
            options = {}
            columns.each_with_index { |col, ind| options.merge!( col => row[ind] ) }
            obj = self.new
            options.each do |attr, value| 
              obj.send("#{attr}=".to_sym, value) if obj.respond_to?("#{attr}=".to_sym)
            end
            obj.save! # raise errors to the log
            total += 1
          rescue => e
            RAILS_DEFAULT_LOGGER.debug "Problems at #{self.name} #{e}"
          end
        end
      end
    ensure
      # turn on Replica tracking
      Replica.track_replica = true 
      ActiveRecord::Base.record_userstamps = true
      ActiveRecord::Base.record_timestamps = true
    end
    total
  end
end

module ActiveRecord
  class CSVImportException < Exception; end
end